﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Agile.Service.Rbac {
    ///<summary>
    ///用户
    ///</summary>
    public interface IUserService:IRepository<User> {
        void Switch(string Id);
        User GetByName(string account);
        List<User> GetUsers(string orgId);
        void ResetPassword(string userid,string defaultPassword);
        void UserRole(string userids,string[] roleIds);
    }
    ///<summary>
    ///用户
    ///</summary>
    public partial class UserService:BaseRepository<User>, IUserService {

        private readonly IRelevanceService _relevanceService;
        public UserService(IRelevanceService relevanceService) {
            _relevanceService = relevanceService;
        }

        public User GetByName(string account) {
            var user = DBA.GetFirstOrDefault<User>(p => p.Account == account);
            return user;
        }

        public void Switch(string Id) {
            var model = Find(Id);
            if(model != null) {
                if(model.Status > 0) {
                    model.Status = 0;
                } else {
                    model.Status = 1;
                }
                Update(model);
            }
        }

        public List<User> GetUsers(string orgId) {
            string sql = "SELECT u.* FROM rbac_user u";
            if(!string.IsNullOrWhiteSpace(orgId)) {
                sql = @"SELECT u.* FROM rbac_user u
INNER JOIN base_relevance r ON u.ID = r.FirstId
INNER JOIN rbac_organize o ON r.SecondId = o.ID WHERE r.[Key]='" + Define.USERORG + "' AND r.SecondId='" + orgId + "' ";

            }
            var users = DBA.Query<User>(sql);
            return users.ToList();
        }

        public void ResetPassword(string userid,string defaultPassword) {

            string[] str = userid.Split(",");
            string sql = "UPDATE " + TableName + " SET Password='"+ defaultPassword + "' WHERE ID IN(" + str.ToSql(false) + ")";
            DBA.ExecuteNonQuery(sql);
        }

        public void UserRole(string userids,string[] roleIds) {
            string[] _userids = userids.Split(",");
            for(int i = 0;i < roleIds.Length;i++) {
                string keyValue = roleIds[i];
                _relevanceService.UnAssign(new AssignReq { type = Define.USERROLE,firstId = keyValue });
                _relevanceService.AssignRoleUsers(new AssignRoleUsers {
                    RoleId = keyValue,
                    UserIds = _userids,
                    IsDelete = true

                });
            }
        }
    }
}

